/*
 * Copyright (C) 2009 Georgios J. Georgopoulos, All rights reserved.
 * 
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 3 of the License, or (at your option) any
 * later version.
 * 
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.gwt.mosaic.xul.client.ui;

import java.util.List;

import org.gwt.mosaic.ui.client.DeckLayoutPanel;

import com.google.gwt.user.client.ui.Widget;

/**
 * An element that displays only one of its children at a time. The {@code
 * selectedIndex} attribute determines which child is displayed.
 * 
 * @author georgopoulos.georgios(at)gmail.com
 * 
 */
public class Deck extends Container {
  private static final long serialVersionUID = -4629114232224962068L;

  private transient DeckLayoutPanel deck = null;

  // -----------------------------------------------------------------------
  /**
   * Gets and sets the index of the currently selected panel. The first item is
   * at index 0.
   */
  public static final String SELECTED_INDEX = "selectedIndex";

  public Integer getSelectedIndex() {
    return getInteger(SELECTED_INDEX);
  }

  public void setSelectedIndex(int selectedIndex) {
    putInteger(SELECTED_INDEX, selectedIndex);
  }

  // -----------------------------------------------------------------------
  public Deck() {
    super();
  }

  // -----------------------------------------------------------------------
  @Override
  protected Widget createUI() {
    if (deck == null) {
      deck = new DeckLayoutPanel();
      deck.setStyleName("xul-Deck");
    }

    syncUI(deck);

    return deck;
  }

  // -----------------------------------------------------------------------
  @Override
  protected void syncUI(Widget ui) {
    super.syncUI(ui);
    
    deck.clear();
    
    final List<Element> elementsWithUI = Container.searchForElementsWithUI(this);
    for (Element element : elementsWithUI) {
      deck.add(element.createUI());
    }

    if (getAttributeMap().containsKey(SELECTED_INDEX)) {
      deck.showWidget(getSelectedIndex());
    } else if (deck.getWidgetCount() > 0) {
      deck.showWidget(1);
    }
  }

}
